package com.transcargo.action;

import java.sql.SQLException;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.transcargo.errors.ErrorList;
import com.transcargo.data.Cache;
import com.transcargo.db.db;
import com.transcargo.db.dbException;
import com.transcargo.users.Transport;
import com.transcargo.users.TransportNotFoundException;

public class EditTruckAction extends AuthAction {
    private String cargo_type = "";
    private String volume = "";
    private String tonnage = "";
    private String length = "";
    private String height = "";
    private String width = "";
    private String tir = "";
    private String ekmt = "";
    private String adr = "";
    private String name = "";
    private String loading = "";
    private int id = 0;

    private void servletGetValues(HttpServletRequest request) throws ServletParametersException, ServletActionException {
		String id = request.getParameter("id");
		this.id = Integer.parseInt(id);
        cargo_type = request.getParameter("cargo_type");
        volume = request.getParameter("volume");
        tonnage = request.getParameter("tonnage");
        length = request.getParameter("length");
        height = request.getParameter("height");
        width = request.getParameter("width");
        tir = request.getParameter("tir");
        ekmt = request.getParameter("ekmt");
        adr = request.getParameter("adr");
        if (tir != null && tir.equals("on")) tir="1"; else tir="0";
        if (ekmt != null && ekmt.equals("on")) ekmt="1"; else ekmt="0";

        Iterator<String> it = Cache.getTransportLoadings().keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            String b = request.getParameter("load" + key);
            if (b != null && b.equals("on")) loading = loading.concat(loading.length() > 0 ? "," + key : key);
        }
        try {
			Transport tr = new Transport(this.id, User_Id, dbase);
        } catch (TransportNotFoundException e) {
        	throw new ServletParametersException("Invalid transport id");
        } catch (dbException e) {
        	throw new ServletActionException();
		}
    }
    private void servletValidateValues() throws ServletValidationException {
        try {
            if (length.length() > 0) {
                length = length.replace(",", ".");
                if (Float.parseFloat(length) == 0) throw new ServletValidationException(ErrorList.ERROR_STR_INVALID_LENGTH);
            }

        } catch (NumberFormatException e) {
            throw new ServletValidationException(ErrorList.ERROR_STR_INVALID_LENGTH);
        }
        try {
            if (width.length() > 0) {
                width = width.replace(",", ".");
                if (Float.parseFloat(width) == 0) throw new ServletValidationException(ErrorList.ERROR_STR_INVALID_WIDTH);
            }

        } catch (NumberFormatException e) {
            throw new ServletValidationException(ErrorList.ERROR_STR_INVALID_WIDTH);
        }
        try {
            if (height.length() > 0) {
                height = height.replace(",", ".");
                if (Float.parseFloat(height) == 0) throw new ServletValidationException(ErrorList.ERROR_STR_INVALID_HEIGHT);
            }

        } catch (NumberFormatException e) {
            throw new ServletValidationException(ErrorList.ERROR_STR_INVALID_HEIGHT);
        }

        if (cargo_type.length() == 0 || Integer.parseInt(cargo_type) == 0) throw new ServletValidationException(ErrorList.ERROR_STR_INVALID_CARGO);
        if (loading.length() == 0) throw new ServletValidationException(ErrorList.ERROR_STR_LOADING_MISSING);
        if (volume.length() == 0 || Integer.parseInt(volume) == 0) throw new ServletValidationException(ErrorList.ERROR_STR_VOLUME_MISSING);
        if (tonnage.length() == 0 || Integer.parseInt(tonnage) == 0) throw new ServletValidationException(ErrorList.ERROR_STR_TONNAGE_MISSING);
        if (adr.length() > 1 && (Integer.parseInt(adr) == 0 || Integer.parseInt(adr) > 9)) throw new ServletValidationException(ErrorList.ERROR_STR_INVALID_ADR);
    }
    private void servletExecuteAction() throws ServletActionException {
        db.PreStatement pre = null;
        try {
			pre = dbase.CreateStatement("CALL UpdateTruck(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
			pre.Insert(id);
            pre.Insert(cargo_type);
            pre.Insert(loading);
            if (height != null && height.length() > 0) pre.Insert(Float.parseFloat(height)); else pre.Insert(null);
            if (width != null && width.length() > 0)pre.Insert(Float.parseFloat(width)); else pre.Insert(null);
            if (length != null && length.length() > 0)pre.Insert(Float.parseFloat(length)); else pre.Insert(null);
            pre.Insert(tir);
            pre.Insert(ekmt);
            if (adr != null && adr.length() > 0) pre.Insert(Integer.parseInt(adr)); else pre.Insert(0);
            pre.Insert(Integer.parseInt(tonnage));
            pre.Insert(Integer.parseInt(volume));
            dbase.executeUpdate(pre);
        } catch (SQLException e) {
			System.out.println("SQL exception: " + e.getMessage());
			throw new ServletActionException();
		} catch (dbException e) {
			System.out.println("Database exception: " + e.getMessage());
			throw new ServletActionException();
		}
    }
    public void processAction(HttpServletRequest request, HttpServletResponse response) throws ServletException {
		try {
            servletGetValues(request);
            servletValidateValues();
            servletExecuteAction();
            sendRedirect(response, "trucks.jsp?i=1");
	    } catch (ServletParametersException e) {
            if (e.getMessage() != null) {
                sendError(response, new Exception(e.getMessage()));
            } else {
                sendRedirect(response, "trucks.jsp");
            }
        }  catch (ServletValidationException e) {
            sendError(response, new Exception(e.getMessage()));
        }  catch (ServletActionException e) {
            sendError(response, new Exception("" + ErrorList.ERROR_STR_GENERIC + dbase.getError()));
        }
    }
}
